package com.sunday.common.sentinel.study.e7_Cluster;

import com.alibaba.csp.sentinel.slots.block.ClusterRuleConstant;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * http://sentinelguard.io/zh-cn/docs/cluster-flow-control.html
 */
@Slf4j
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        initFlowQpsRule();
    }

    private static void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource("helloAnother");
        // set limit qps to 20
        rule1.setCount(1);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");

        /**
         * 集群流控规则
         * 规则
         * FlowRule 添加了两个字段用于集群限流相关配置：
         *
         * private boolean clusterMode; // 标识是否为集群限流配置
         * private ClusterFlowConfig clusterConfig; // 集群限流相关配置项
         */
        rule1.setClusterMode(true);
        ClusterFlowConfig clusterFlowConfig = new ClusterFlowConfig();
        clusterFlowConfig.setFlowId(1L);
        clusterFlowConfig.setThresholdType(ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL);
        clusterFlowConfig.setStrategy(ClusterRuleConstant.FLOW_CLUSTER_STRATEGY_NORMAL);
        clusterFlowConfig.setFallbackToLocalWhenFail(true);

        rule1.setClusterConfig(clusterFlowConfig);
        log.info("=========== {}", rule1);
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }

}
